package com.cxh.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;


/**
 * @类功能说明：文本记录日志
 */
public class LogUtil {
	// 日志保存路径
	private static String log_path = getLogBasePath();
	// 日志文件名（前部分）
	private static String log_name = "Mavendata_";
	// 日志是否输出到控制台
	private static boolean console_out = true;
	/*
	 * yyyy-MM: 每个月更新一个log日志 yyyy-ww: 每个星期更新一个log日志 yyyy-MM-dd: 每天更新一个log日志
	 * yyyy-MM-dd-a: 每天的午夜和正午更新一个log日志 yyyy-MM-dd-HH: 每小时更新一个log日志
	 * yyyy-MM-dd-HH-mm: 每分钟更新一个log日志
	 */
	// 更新日志的频率，每月更新一次
	private static String update_hz = "yyyy-MM";
	// 单个日志文件最大大小 10M
	private static long max_log_size = 1024 * 1024 * 10;

	/** debug记录日志，Constant.IS_DEBUG==false时不记录日志 */
	public static void debug(String msg) {
		//if (Constant.IS_DEBUG) {
			runWrite(msg, log_path, log_name + "_debug");
		//}
	}

	public static void info(String msg) {
		runWrite(msg, log_path, log_name + "_info");
	}

	public static void error(String msg) {
		runWrite(msg, log_path, log_name + "_error");
	}

	public static String printStackTraceToString(Throwable t) {
	    StringWriter sw = new StringWriter();
	    t.printStackTrace(new PrintWriter(sw, true));
	    return sw.getBuffer().toString();
	}
	
	public static void exception(Exception e) {
		String errorMessage = e.getMessage() + "";
		String printStackTraceToString = printStackTraceToString(e);
		try {
			//StackTraceElement[] eArray = e.getCause().getStackTrace();
			StackTraceElement[] eArray = e.getStackTrace();
			for (int i = 0; i < eArray.length; i++) {
				String className = e.getCause().getStackTrace()[i].getClassName();
				String MethodName = e.getCause().getStackTrace()[i].getMethodName();
				int LineNumber = e.getCause().getStackTrace()[i].getLineNumber();
				errorMessage = errorMessage + "\n\t---" + className + "." + MethodName + ",\tline:" + LineNumber;
			}
		} catch (Exception e2) {
			e2.printStackTrace();
			errorMessage = "NullPointException:" + e.toString();
		}

		//runWrite(errorMessage, log_path, log_name + "_exception");
		runWrite(printStackTraceToString, log_path, log_name + "_exception");
	}

	/**
	 * 日志根目录
	 * 
	 * @return
	 */
	public static String getLogBasePath() {
		 String s =
		 Thread.currentThread().getContextClassLoader().getResource("").getPath();
		 s = s.substring(0, s.indexOf("WEB-INF")) + "log" + File.separator;
		/*String s = "/yftlog/";*/
		return s;
	}

	/**
	 * 写日志
	 * 
	 * @param sWord
	 *            要写入日志里的文本内容
	 */
	public static void logResult(String sWord) {
		runWrite(sWord, log_path, log_name);
	}

	/**
	 * 写日志
	 * 
	 * @param sWord
	 *            要写入日志里的文本内容
	 */
	public static void logException(String sWord) {
		runWrite(sWord, log_path, log_name + "_exception");
	}

	public static void writeLog(String sWord, String logPath, String logName) {
		FileWriter writer = null;
		try {
			File dir = new File(logPath);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			String dt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
			File f = new File(logPath + logName + "_" + new SimpleDateFormat(update_hz).format(new Date()) + ".txt");
			if (!f.exists()) {
				f.createNewFile();
				sWord = "汽车机器人 日志\r\n" + "[" + dt + "]\t" + sWord;
			} else {
				long logSize = f.length();
				// 文件大小超过10M，备份
				if (logSize >= max_log_size) {
					String backLogName = logPath + logName
							+ new SimpleDateFormat("_yyyy-MM-dd.HHmmss.SSS").format(new Date()) + ".txt";
					f.renameTo(new File(backLogName));
				}
			}
			writer = new FileWriter(f, true);
			writer.write("[" + dt + "]\t" + sWord + "\r\n");
			writer.flush();
			if (console_out) {
				System.out.println("[" + dt + "]\t" + sWord);
			}
		} catch (Exception e) {
			System.out.println("记录日志异常：" + e.toString());
			e.printStackTrace();
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static void runWrite(final String sWord, final String logPath, final String logName) {
		new Thread() {
			public void run() {
				writeLog(sWord, logPath, logName);
			}
		}.start();
	}
	
	private final static Logger GATELOG = LoggerFactory.getLogger("ACP_SDK_LOG");
	private final static Logger GATELOG_ERROR = LoggerFactory.getLogger("SDK_ERR_LOG");
	private final static Logger GATELOG_MESSAGE = LoggerFactory.getLogger("SDK_MSG_LOG");

	final static String LOG_STRING_REQ_MSG_BEGIN = "============================== SDK REQ MSG BEGIN ==============================";
	final static String LOG_STRING_REQ_MSG_END = "==============================  SDK REQ MSG END  ==============================";
	final static String LOG_STRING_RSP_MSG_BEGIN = "============================== SDK RSP MSG BEGIN ==============================";
	final static String LOG_STRING_RSP_MSG_END = "==============================  SDK RSP MSG END  ==============================";

	/**
	 * 记录普通日志
	 * 
	 * @param cont
	 */
	public static void writeLog(String cont) {
		GATELOG.info(cont);
	}

	/**
	 * 记录ERORR日志
	 * 
	 * @param cont
	 */
	public static void writeErrorLog(String cont) {
		GATELOG_ERROR.error(cont);
	}

	/**
	 * 记录ERROR日志
	 * 
	 * @param cont
	 * @param ex
	 */
	public static void writeErrorLog(String cont, Throwable ex) {
		GATELOG_ERROR.error(cont, ex);
	}

	/**
	 * 记录通信报文
	 * 
	 * @param msg
	 */
	public static void writeMessage(String msg) {
		GATELOG_MESSAGE.info(msg);
	}

	/**
	 * 打印请求报文
	 * 
	 * @param reqParam
	 */
	public static void printRequestLog(Map<String, String> reqParam) {
		writeMessage(LOG_STRING_REQ_MSG_BEGIN);
		Iterator<Entry<String, String>> it = reqParam.entrySet().iterator();
		while (it.hasNext()) {
			Entry<String, String> en = it.next();
			writeMessage("[" + en.getKey() + "] = [" + en.getValue() + "]");
		}
		writeMessage(LOG_STRING_REQ_MSG_END);
	}

	/**
	 * 打印响应报文.
	 * 
	 * @param res
	 */
	public static void printResponseLog(String res) {
		writeMessage(LOG_STRING_RSP_MSG_BEGIN);
		writeMessage(res);
		writeMessage(LOG_STRING_RSP_MSG_END);
	}


}
